<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->

      <div v-if="crud.props.searchToggle">
        <!--- 搜索 --->
        <el-input v-model="query.deptName" clearable size="small" placeholder="输入机构名称搜索" style="width: 200px" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select v-model="query.enabled" clearable size="small" placeholder="状态" class="filter-item" style="width: 90px" @change="crud.toQuery">
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <rrOperation />
      </div>

      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="480px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">

          <el-form-item label="部门名称">
            <el-input v-model="form.deptName" style="width: 370px;" />
          </el-form-item>

          <el-form-item label="部门编码">
            <el-input v-model="form.deptCode" style="width: 370px;" />
          </el-form-item>

          <el-form-item label="部门排序">
            <el-input v-model="form.orderRank" style="width: 370px;" />
          </el-form-item>

          <el-form-item label="状态" prop="enabled">
            <el-radio-group v-model="form.enabled" size="mini" controls-position="right" style="width: 178px">
              <el-radio-button label="true">启用</el-radio-button>
              <el-radio-button label="false">禁用</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="上级部门" prop="pid">
            <treeselect v-model="form.pid" :load-options="loadDepartment" :options="depts" :normalizer="normalizer" style="width: 370px" placeholder="选择上级部门" />
          </el-form-item>

          <el-form-item label="所属机构" prop="orgId">
            <treeselect v-model="form.orgId" :load-options="loadOrg" :options="orgs" :normalizer="normalizer" style="width: 370px" placeholder="选择所属机构" />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" lazy :load="getDepartments" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :data="crud.data" row-key="id" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderRank" label="排序号" />
        <el-table-column prop="deptName" label="部门名称" />
        <el-table-column prop="deptCode" label="部门编码" />
        <el-table-column label="状态" align="center" prop="enabled">

        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            :disabled="scope.row.id === 1"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            @change="changeEnabled(scope.row, scope.row.enabled)"
          />
        </template>
        </el-table-column>

        <el-table-column v-if="checkPer(['admin','hd:edit','hd:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudOrg from '@/api/system/org'
import crudDepartment from '@/api/system/department'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = {
  id: null,
  delFlag: null,
  parentId: null,
  orderRank: 999,
  deptName: null,
  pid: null,
  orgId: null,
  deptCode: null,
  versionNo: null,
  childrenSize: null,
  inheritLevel: null,
  enabled: true
}
export default {
  name: 'department',
  components: { Treeselect, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '部门管理', url: 'api/sys/department/page', idField: 'id', sort: 'id,desc', crudMethod: { ...crudDepartment } })
  },
  data() {
    return {
      depts: [],
      orgs: [],
      permission: {
        add: ['admin', 'sys:department:add'],
        edit: ['admin', 'sys:department:edit'],
        del: ['admin', 'sys:department:del']
      },
      rules: {
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '启用' },
        { key: 'false', display_name: '禁用' }
      ]
    }
  },
  methods: {
    getDepartments(tree, treeNode, resolve) {
      const params = { pid: tree.id }
      setTimeout(() => {
        crudDepartment.getDepartments(params).then((res) => {
          resolve(res)
        })
      }, 100)
    },
    getAllDepartment(id) {
      crudDepartment.findAll(id).then((res) => {
        const children = res.map(function (obj) {
          if (!obj.leaf && !obj.children) {
            obj.children = null
          }
          return obj
        })
        this.depts = [{ id: 0, name: '顶级类目', children: children }]
      })
    },
    getAllOrg(id) {
      crudOrg.findAll(id).then((res) => {
        const children = res.map(function(obj) {
          if (!obj.leaf && !obj.children) {
            obj.children = null
          }
          return obj
        })
        this.orgs = [{ id: 0, name: '顶级类目', children: children }]
      })
    },
    // 获取弹窗内部门数据
    loadDepartment({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudDepartment
          .getDepartmentTree({ pid: parentNode.id == '0' ? null : parentNode.id })
          .then((res) => {
            parentNode.children = res.map(function (obj) {
              if (!obj.leaf) {
                obj.children = null
              }
              return obj
            })
            setTimeout(() => {
              callback()
            }, 100)
          })
      }
    },
    // 获取弹窗内机构数据
    loadOrg({ action, parentNode, callback }) {

      if (action === LOAD_CHILDREN_OPTIONS) {
        crudOrg
          .getOrgTree({ pid: parentNode.id == '0' ? null : parentNode.id })
          .then((res) => {
            parentNode.children = res.map(function (obj) {
              if (!obj.leaf) {
                obj.children = null
              }
              return obj
            })
            setTimeout(() => {
              callback()
            }, 100)
          })
      }
    },


    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

     // 改变状态
     changeEnabled(data, val) {
      console.info(data)
      this.$confirm(
        '此操作将 "' + val
          ? '禁用 '
          : '启用 ' + data.name + ' 部门, 是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
            crudDepartment
            .edit(data)
            .then((res) => {
              this.crud.notify('设置成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
            })
            .catch((err) => {
              data.enabled = !data.enabled
              console.log(err.response.message)
            })
        })
        .catch(() => {
          data.enabled = !data.enabled
        })
    },

    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.afterToCU](crud, form) {
      this.depts = []
      this.orgs = []
      if (form.id != null) {
        if (form.pid === null) {
          form.pid = 0
        }
        this.getAllOrg(form.orgId)
        this.getAllDepartment(form.id)
      } else {
        this.depts.push({ id: 0, name: '顶级类目', children: null })
        crudOrg.getOrgTree(null).then((res) => {
          this.orgs = res
        })
      }
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {

      if (this.form.orgId == null) {
        this.$message({
          message: '所属机构不能为空',
          type: 'warning'
        })
        return false
      }

      return true
    },
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>
